const fs = require('fs')
const path = require('path')

const copyFile = (src, dst) => {
  const readable = fs.createReadStream(src)
  const writable = fs.createWriteStream(dst)
  readable.pipe(writable)
}
/**
 * 复制文件夹到指定目录
 * @param {string} src 将要复制的文件目录路径
 * @param {string} dst 将要复制到的文件目录路径
 * @param {Array<string>} blackList 文件名称黑名单
 */
exports.copySync = (src, dst, blackList = []) => {
  return new Promise((resolve, reject) => {
    fs.readdir(src, { encoding: 'utf-8' }, (err, files) => {
      if (err) {
        // file
        copyFile(src, dst)
        resolve()
      } else {
        // folder
        fs.mkdirSync(dst, { recursive: true })
        Promise.all(files.filter(name => !blackList.includes(name)).map(name => {
          return exports.copySync(path.join(src, name), path.join(dst, name))
        })).then(resolve).catch(reject)
      }
    })
  })
}

/**
 * 修改指定路径的文件内容
 * @param {string} filePath 
 * @param {(data: string) => string} handler 处理读到的文件内容，并返回写入文件的新内容字符串
 * @returns {Promise<void>}
 */
exports.editSync = (filePath, handler) => {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => {
      if (err) {
        reject(err)
      } else {
        fs.writeFile(filePath, handler(data), { encoding: 'utf-8' }, (err) => {
          if (err) {
            reject(err)
          } else {
            resolve()
          }
        })
      }
    })
  })
}